package com.kool.kmqtt.server.repository;

import com.kool.kmqtt.server.ServerConfig;
import com.kool.kmqtt.server.constant.RepositoryTypeEnum;
import com.kool.kmqtt.server.exception.AppException;
import com.kool.kmqtt.server.exception.ErrorCode;
import com.kool.kmqtt.server.repository.etcd.EtcdRepository;
import com.kool.kmqtt.server.repository.local.DefaultRepository;
import com.kool.kmqtt.server.repository.redis.RedisRepository;
import lombok.extern.slf4j.Slf4j;

/**
 * 仓库工厂类
 */
@Slf4j
public class RepositoryFactory {
    private static volatile Repository repository;
    private static final Object lock = new Object();

    /**
     * 获取仓库实例
     *
     * @return
     */
    public static Repository getRepository() {
        if (repository == null) {
            synchronized (lock) {
                if (repository == null) {

                    // 根据配置创建仓库实例，默认用DefaultRepository
                    String repoType = ServerConfig.getInstance().getRepositoryType();
                    if (RepositoryTypeEnum.DEFAULT.getType().equals(repoType)) {
                        repository = new DefaultRepository();
                    } else if (RepositoryTypeEnum.ETCD.getType().equals(repoType)) {
                        repository = new EtcdRepository();
                    } else if (RepositoryTypeEnum.REDIS.getType().equals(repoType)) {
                        repository = new RedisRepository();
                    } else {
                        throw new AppException(ErrorCode.UNSUPPORTED_REPOSITORY_TYPE, repoType);
                    }
                }
            }
        }
        return repository;
    }
}
